package naga.x.net.proxy.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import naga.x.net.codec.PacketEncoder;
import naga.x.net.proxy.ProxyPacket;

public class ProxyPacketEncoder extends ProtocolEncoderAdapter implements PacketEncoder {

	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		Object buf = encode(session, message);
		if (buf != null) {
			out.write(buf);
		}
	}

	@Override
	public Object encode(IoSession session, Object packet) {
		if (packet instanceof ProxyPacket) {
			ProxyPacket proxy = (ProxyPacket) packet;
			IoBuffer data = proxy.getData();
//			data.flip();
			int dataLen = 11 + data.remaining();
			IoBuffer buf = IoBuffer.allocate(17 + dataLen).setAutoExpand(true);
			buf.put(ProxyPacket.HEAD);
			buf.putInt(dataLen);
			buf.putShort(proxy.getOpCode());
			buf.putInt(proxy.getSessionId());
			buf.putInt(proxy.getSerial());
			buf.put(proxy.getType());
			buf.put(data);
			buf.flip();
			return buf;
		}
		return null;
	}

}
